package com.bill.httpdemo;
 
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
 
import java.net.URI;
 
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
 
    /**
     * 读取客户端请求，并且返回给客户端数据的方法
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
 
        if(!(httpObject instanceof HttpRequest)) {
            return;
        }
 
        System.out.println("excute channelRead0");
 
        HttpRequest httpRequest = (HttpRequest) httpObject;
 
        URI uri = new URI(httpRequest.uri());
        System.out.println(uri.getPath());
 
        ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK, content);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
 
        channelHandlerContext.writeAndFlush(response);
    }
}
 